package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        1、获取本次请求的URI
        String uri = request.getRequestURI();
//        2、判断本次请求是否需要处理
        String[] urls = {"/employee/login", "/employee/logout", "/backend/**", "/front/**", "/user/login", "/user/sendMsg"};
//        3、如果不需要处理，则直接放行
        if (checkUrl(uri, urls)){
            log.info("本次{}请求不需要处理",request.getRequestURI());
            filterChain.doFilter(request, response);
            return;
        }
//        4-1、判断employee登录状态，如果已登录，则直接放行
        Object employee = request.getSession().getAttribute("employee");
        if(employee != null){
            log.info("用户已登录，用户id为{}", request.getSession().getAttribute("employee"));
            Long id = (Long) request.getSession().getAttribute("employee");
            BaseContext.setId(id);
            filterChain.doFilter(request, response);
            return;
        }
        // 4-2、user，如果已登录，则直接放行
        Object user = request.getSession().getAttribute("user");
        if(user != null){
            log.info("用户已登录，用户id为{}", request.getSession().getAttribute("user"));
            Long id = (Long) request.getSession().getAttribute("user");
            BaseContext.setId(id);
            filterChain.doFilter(request, response);
            return;
        }
//        5、如果未登录则返回未登录结果
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean checkUrl(String uri, String[] urls){
        for (String url : urls) {
            if(PATH_MATCHER.match(url, uri)){
                return true;
            }
        }
        return false;
    }
}
